<?php
declare (strict_types=1);

namespace app\api\controller;

use app\api\model\Goods;
use app\api\model\SpecGoods;
use Predis\Client;
use think\facade\Validate;
use think\response\Json;

class CartController
{

    //购物车
    protected $redis;

    public function __construct()
    {
        $this->redis = new Client([
            'scheme' => config('redis.scheme'),
            'host' => config('redis.host'),
            'port' => config('redis.port'),
            'cache' => config('redis.cache'),
            'password' => config('redis.password')
        ]);
    }

    /**
     * 添加购物车接口
     */
    public function addCart()
    {
        //1、接收数据
        $param = input();

        //2、验证数据
        $validate = Validate::rule([
            'user_id' => 'require',
            'goods_id' => 'require',
            'value_ids' => 'require',
            'number' => 'require',
        ]);
        if (!$validate->check($param)) return json(['code' => 4003, 'msg' => $validate->getError(), 'data' => '']);

        //3、查询商品
        $goodsData = (new Goods())->find($param['goods_id']);
        //4、查询商品的规格信息
        $specGoodsData = (new SpecGoods())->getSpecGoodsInfo($param['goods_id'], $param['value_ids']);
        //添加购物车的数据
        $addCartData = [
            'spec_goods_id' => $specGoodsData->id,
            'goods_name' => $goodsData->goods_name,
            'goods_img' => $goodsData->goods_img,
            'value_names' => $specGoodsData->value_names,
            'price' => $specGoodsData->price,
            'number' => $param['number'],
            'is_default' => 1 //是否选中 1选中 0未选中
        ];

        //5、查询redis中hash购物车表
        $cartInfo = $this->redis->hget('cart', $param['user_id']);

        //6、判断是否已存在该用户
        if (!$cartInfo) {
            //未加入添加
            $this->redis->hsetnx('cart', $param['user_id'], json_encode([$addCartData]));
            return json(['code' => 200, 'msg' => '成功', 'data' => '']);
        }

        //存在 判断商品规格是否已存在
        $cartInfoArr = \Qiniu\json_decode($cartInfo);
        $is_exit = 0;
        //循环判断
        foreach ($cartInfoArr as $k => &$v) {
            //存在加一
            if ($v->spec_goods_id == $addCartData['spec_goods_id']) {
                //购买数量加
                $v->number += 1;
                break;
            } else {
                //购物车中无该规格
                $is_exit += 1;
            }
        }
        if ($is_exit == count($cartInfoArr)) {
            array_push($cartInfoArr, $addCartData);
        }
        //重新添加到hash
        $this->redis->hset('cart', $param['user_id'], json_encode($cartInfoArr));

        return json(['code' => 200, 'msg' => '添加成功', 'data' => '']);
    }

    /**
     * 购物车列表接口
     */
    public function cartList()
    {
        //1、接收用户
        $uid = input('user_id');

        //2、验证数据
        if (empty($uid) || !isset($uid)) return json(['code' => 4003, 'msg' => '请先登录', 'data' => '']);

        //3、获取数据
        $cartList = $this->redis->hget('cart', $uid);
        $cartList = \Qiniu\json_decode($cartList);
        return json(['code' => 200, 'msg' => '展示成功', 'data' => $cartList]);
    }

    /**
     * 删除购物车商品
     */
    public function cartDel()
    {
        //1、接收数据
        $param = input();

        //2、验证数据
        $validate = Validate::rule([
            'user_id' => 'require',
            'spec_goods_id' => 'require'
        ]);
        if (!$validate->check($param)) return json(['code' => 4003, 'msg' => $validate->getError(), 'data' => '']);

        //3、获取用户购物车
        $userCartData = $this->redis->hget('cart', $param['user_id']);
        $userCartData = \Qiniu\json_decode($userCartData);
        $newUserCartData = [];

        //4、循环判断
        foreach ($userCartData as $k => &$v) {
            //删除数据
            if ($v->spec_goods_id != $param['spec_goods_id']) {
                array_push($newUserCartData, $v);
            }
        }
        //5、重新存储
        $this->redis->hset('cart', $param['user_id'], json_encode($newUserCartData));

        return json(['code' => 200, 'msg' => '删除成功', 'data' => '']);
    }

    /**
     * 修改购物车商品规格数量接口
     */
    public function cartupdate()
    {
        //1、接收数据
        $param = input();

        //2、验证数据
        $validate = Validate::rule([
            'user_id' => 'require',
            'spec_goods_id' => 'require',
            'number' => 'require',
            'is_default' => 'require'
        ]);
        if (!$validate->check($param)) return json(['code' => 4003, 'msg' => $validate->getError(), 'data' => '']);

        //3、获取用户购物车
        $userCartData = $this->redis->hget('cart', $param['user_id']);
        $userCartData = \Qiniu\json_decode($userCartData);

        //4、循环判断
        foreach ($userCartData as $k => &$v) {
            //修改数据
            if ($v->spec_goods_id == $param['spec_goods_id']) {
                $v->number = $param['number'];
                $v->is_default = $param['is_default'];
            }
        }
        //5、重新存储
        $this->redis->hset('cart', $param['user_id'], json_encode($userCartData));

        return json(['code' => 200, 'msg' => '修改成功', 'data' => '']);
    }

    /**
     * 订单页面购物车中商品展示接口
     */
    public function orderGoodsList()
    {
        //1、接收数据
        $param = input();

        //2、验证数据
        $validate = Validate::rule([
            'user_id' => 'require',
        ]);
        if (!$validate->check($param)) return json(['code' => 4003, 'msg' => $validate->getError(), 'data' => '']);

        //3、查询购物车中选中的商品规格信息
        $cartGoodsData = \Qiniu\json_decode($this->redis->hget('cart', $param['user_id']));
        //4、存储购物车中选中的的商品规格
        $selectdGoods = [];
        //5、循环判断
        foreach ($cartGoodsData as $k => $v) {
            if ($v->is_default == 1) {
                $selectdGoods[] = $v;
            }
        }

        return json(['code' => 200, 'msg' => '查询成功', 'data' => $selectdGoods]);
    }
}
